package handler

import (
	"context"
	"math/rand"
	"model"
	"pkg"
	"strconv"
	"time"
	"user-srv/user/pb"
)

type UserHandler struct {
	*pb.UnimplementedUserServer
}

// 用户注册
func (*UserHandler) UserAdd(ctx context.Context, rep *pb.UserAddReq) (*pb.UserAddResp, error) {
	p := rand.Intn(9000) + 1000
	pwd := pkg.Md5(rep.Password + strconv.Itoa(p))
	pone := model.User{
		ClassId:  int(rep.ClassId),
		Username: rep.Username,
		Password: pwd,
		Phone:    rep.Phone,
		Age:      int(rep.Age),
		Sex:      int(rep.Sex),
		Slat:     strconv.Itoa(p),
	}
	err := pone.UserAdd()
	if err != nil {
		return nil, err
	}
	return &pb.UserAddResp{
		ID:       int64(pone.ID),
		ClassId:  int64(pone.ClassId),
		Username: pone.Username,
		Password: pone.Password,
		Phone:    pone.Phone,
		Age:      int64(pone.Age),
		Sex:      int64(pone.Sex),
		Slat:     pone.Slat,
	}, nil
}

// 用户登录
func (*UserHandler) UserLogin(ctx context.Context, rep *pb.UserLoginReq) (*pb.UserLoginResp, error) {
	pone := model.User{Username: rep.Username}
	res, err := pone.UserLogin()
	if err != nil {
		return nil, err
	}
	token, err := pkg.GetJwtToken("2204a", time.Now().Unix(), 86400, strconv.Itoa(int(res.ID)))
	if err != nil {
		return nil, err
	}
	return &pb.UserLoginResp{
		Code: 200,
		Msg:  "登录成功",
		Data: token,
	}, nil
}
